<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="状态">
          <el-select
            style="width: 100%"
            v-model="searchParam.abnormalStatus"
            placeholder="请选择状态"
            filterable
            clearable
          >
            <el-option
              v-for="item in useDictionary('abnormalStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="填写日期">
          <el-date-picker
            v-model="searchParam.fillDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getFillDate"
          />
        </el-form-item>
        <el-form-item label="工序">
          <el-select
            style="width: 100%"
            v-model="searchParam.process"
            placeholder="请选择工序"
            filterable
            clearable
          >
            <el-option
              v-for="item in useDictionary('ProcessType')"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料">
          <el-select
            style="width: 100%"
            v-model="searchParam.materialName"
            placeholder="请选择物料"
            clearable
            filterable
            :filter-method="materialFilter"
          >
            <el-option
              v-for="item in materialFilteredOptions"
              :key="item.materialName"
              :label="item.materialName"
              :value="item.materialName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="填写部门">
          <el-input
            v-model="searchParam.fillDepartment"
            placeholder="请输入填写部门"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="异常通知单号"
          prop="abnormalCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="状态"
          prop="abnormalStatus"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("abnormalStatus", scope.row.abnormalStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="填写日期"
          prop="fillDate"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="填写部门"
          prop="fillDepartment"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="填写人"
          prop="filler"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="工序"
          prop="process"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("ProcessType", scope.row.process) }}
          </template>
        </el-table-column>
        <el-table-column
          label="成品物料号"
          prop="materialCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="成品名称"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="生产批次"
          prop="productionBatch"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="计划编号"
          prop="planCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="异常数量"
          prop="abnormalNum"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="比例"
          prop="abnormalRatio"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="处理结果"
          prop="dealResult"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="判定人"
          prop="judge"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <qmsabnormalorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import _ from "lodash-es";

defineOptions({
  name: "QMSQMSABNORMALORDER",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/qms/qmsabnormalorder/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {};

const deleteParam = {
  api: "/qms/qmsabnormalorder/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/qmsabnormalorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开异常品工单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改异常品工单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增异常品工单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开异常品工单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "异常品工单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/qms/qmsabnormalorder/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

function getFillDate(data: any) {
  if (data) {
    searchParam.value.fillDateStart = data[0];
    searchParam.value.fillDateEnd = data[1];
  } else {
    searchParam.value.fillDateStart = "";
    searchParam.value.fillDateEnd = "";
  }
}

const materialList = ref([]);

const getMaterialList = async () => {
  const { data } = await request({
    url: "/mdm/mdmmaterial/getList",
    method: "post",
    data: {},
  });
  materialList.value = data;
  materialFilteredOptions.value = data;
};

const materialFilteredOptions = ref<any>([]);

// 使用 debounce 包装过滤方法
const materialFilter = _.debounce((query: any) => {
  if (!query) {
    materialFilteredOptions.value = [...materialList.value];
    return;
  }
  materialFilteredOptions.value = materialList.value.filter((option: any) =>
    option.materialName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);
onMounted(() => {
  getMaterialList();
});
</script>
